<template>
  <div class="user-management">
    <!-- 页头 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>

    </div>

    <!-- 搜索栏 -->
    <el-card class="filter-card">
      <div class="search-bar">
        <el-input
          v-model="searchKey"
          placeholder="搜索用户名"
          clearable
          style="width: 300px;"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
		<el-button type="primary" @click="openAddUserDialog">
        <el-icon><plus /></el-icon>
        添加用户
      </el-button>
      </div>
    </el-card>

    <!-- 用户表格 -->
    <el-table :data="userList.list" border style="width: 100%;">
      <el-table-column prop="pc_user_id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="real_name" label="真实姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="电话号码" />
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
            {{ statusMap[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="openEditUserDialog(scope.row)">编辑</el-button>
          <el-button
            type="text"
            text-color="#ff4d4f"
            @click="handleDeleteUser(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
          v-model:current-page="pagetable.pageNum"
          v-model:page-size="pagetable.pageSize"
          :page-sizes="[5, 10, 15, 50]"
          :size="'default'"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userList.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="isEditMode ? '编辑用户' : '添加用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="formData"
        ref="userForm"
        :rules="formRules"
        label-width="100px"
      >{{formData}}
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="comfPassword">
          <el-input type="password" v-model="formData.comfPassword" placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
        </el-form-item>
		<el-form-item label="邮箱" prop="email">
		  <el-input v-model="formData.email" placeholder="请输入邮箱" />
		</el-form-item>
		<el-form-item label="电话号码" prop="phone">
		  <el-input v-model="formData.phone" placeholder="请输入电话号码" />
		</el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色"  @change="handleRoleChange">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
			  :data-role-type="item.roleType"
            />
          </el-select>
        </el-form-item>
		 <!-- 部门选择框（根据角色类型动态显示） -->
        <el-form-item label="部门" prop="department" v-if="showDepartment">
          <el-cascader v-model="formData.department" placeholder="请选择部门" :options="departmentList" @change="handleChange" :props="props"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="启用" value="1"/>
            <el-radio label="禁用" value="0"/>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch, nextTick, getCurrentInstance } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 全局属性获取（需确保main.js已挂载$axios）
const { proxy } = getCurrentInstance();
let statusMap = {
	0: '禁用',
	1: '启用'
}

let pagetable=ref({
	pageNum:1,
	pageSize:5
	})


const handleSizeChange = (val) => {
  pagetable.value.pageSize=val;
  initData();
}
const handleCurrentChange = (val) => {
  pagetable.value.pageNum=val;
  initData();
}

const handleChange = (value) => {
  console.log(value)
}

// 搜索/分页参数
const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
// 控制部门选择框的显示状态
const showDepartment = ref(false);
// 用户数据 & 角色选项
const userList = ref([]);
const props = {
  checkStrictly: true,
}

const initData = () => {
  proxy.$axios.get(`/pcUser/getPCUserList/${pagetable.value.pageNum}/${pagetable.value.pageSize}`,{params:{username:searchKey.value}})
    .then((res) => {
      if (res.data.code == 0) {
        userList.value = res.data.data;
		console.log(userList.value);
      } else {
        ElMessage.error('数据加载失败：' + res.data.msg);
      }
    })
    .catch((err) => {
      console.error('接口异常：', err);
      ElMessage.error('网络错误，请重试');
    });
};

const handleRoleChange = (role_id) => {
	const selectedRole = roleList.value.find(item => item.value == role_id);
	if (selectedRole) {
		showDepartment.value = selectedRole.roleType === 'doctor';
		if (!showDepartment.value) {
			formData.value.department = '';
		}
	}
}

// 弹窗状态
const dialogVisible = ref(false);
const isEditMode = ref(false);
const currentEditId = ref(null);
const userForm = ref(); // 表单引用

// 表单数据
const formData = ref({
   id:'',
  username: '',
  password: '',
  comfPassword: '',
  realName: '',
  role: '',
  status: '1',
  email: '',
  phone: '',
  department: [], // 部门字段
});

// 密码验证逻辑
const validatePass = (rule, value, callback) => {
  // 编辑模式且密码为空时不验证
  if (isEditMode.value && value === '') {
    callback();
    return;
  }

  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (formData.value.comfPassword !== '') {
    userForm.value?.validateField('comfPassword');
    callback();
  } else {
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  // 编辑模式且密码为空时不验证
  if (isEditMode.value && formData.value.password === '') {
    callback();
    return;
  }

  if (value === '') {
    callback(new Error('请确认密码'));
  } else if (value !== formData.value.password) {
    callback(new Error('密码不一致'));
  } else {
    callback();
  }
};

// 新增模式的验证规则（密码必填）
const baseRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度 3-20 字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  comfPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '真实姓名长度 2-10 字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' }
  ]
};

// 编辑模式的验证规则（密码非必填）
const editRules = {
  ...baseRules,
  password: [
    { required: false, message: '请输入密码（不填则不修改）', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  comfPassword: [
    { required: false, message: '请确认密码（不填则不修改）', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
};

// 用ref存储当前生效的规则
const formRules = ref(baseRules);

// 弹窗关闭时重置表单和规则
watch(() => dialogVisible.value, (newVal) => {
  if (!newVal) {
    // 重置为新增规则

      userForm.value?.resetFields();
      formRules.value = baseRules;

  }
});





// 搜索事件（重置分页）
const handleSearch = () => {
	initData();
  currentPage.value = 1;
};

// 新增弹窗
const openAddUserDialog = () => {
  isEditMode.value = false;
  showDepartment.value=false;
  // 切换为新增规则
  formRules.value = baseRules;
  // 重置表单数据和验证状态

  formData.value = {
	  id:'',
      username: '',
      password: '',
      comfPassword: '',
      realName: '',
      role: '',
      status: '1',
      email: '',
      phone: '',
      department: [],
    };
    userForm.value?.resetFields(); // 保留以清空表单验证状态
  dialogVisible.value=true;
};

// 根据部门ID，递归查找级联选择器所需的完整路径数组
const getCascaderPath = (deptId, departmentList) => {
  if (!deptId) return []; // 无ID时返回空数组

  // 递归逻辑：遍历部门列表，查找匹配的ID并回溯父级
  const findPath = (id, list) => {
    for (const item of list) {
      if (item.value === id) {
        return [id]; // 找到当前节点，返回自身ID
      } else if (item.children && item.children.length > 0) {
        const childPath = findPath(id, item.children); // 递归查找子节点
        if (childPath) {
          // 找到子节点，拼接当前节点ID和子节点路径
          return [item.value, ...childPath];
        }
      }
    }
    return null; // 未找到
  };

  const path = findPath(deptId, departmentList);
  return path || []; // 未找到时返回空数组
};

// 编辑弹窗
const openEditUserDialog = (row) => {

  isEditMode.value = true;
  // 切换为编辑规则
  formRules.value = editRules;
  console.log(row)

  proxy.$axios.get("/pcuserrole/selectRoleIdByPCUserId",{params:{pc_user_id:row.pc_user_id}})
  .then((serverData)=>{
	  if(serverData.data.code==0){
		  const deptPath = getCascaderPath(row.dept_id, departmentList.value);
		  formData.value = {
	id:row.pc_user_id ,
    username: row.username,
    realName: row.real_name,
    status: row.status.toString(),
    email: row.email,
	role:serverData.data.data,
    phone: row.phone,
    password: '',  // 编辑时密码置空
    comfPassword: '',  // 确认密码置空
    department: deptPath
  };
  handleRoleChange(serverData.data.data)
  dialogVisible.value = true;
 userForm.value?.resetFields();
	  }
  })


  // 填充表单数据

  handleRoleChange(row.role_id);


};

// 提交表单（新增/编辑）
const submitForm = () => {
  userForm.value.validate((valid) => {
    if (valid) {
      if (isEditMode.value) {

		  let updateData={
			  pc_user_id:formData.value.id,
			  username:formData.value.username,
			  password:formData.value.password,
			  real_name:formData.value.realName,
			  dept_id:formData.value.department.at(-1),
			  email:formData.value.email,
			  phone:formData.value.phone,
			  status:formData.value.status,
			  role_id:formData.value.role,
		  }
		  console.log(updateData)
           proxy.$axios.put("/pcUser/updatePCUser",updateData)
		   .then((serverData)=>{
			   if(serverData.data.code==0){
				 ElMessage.success('用户编辑成功');
				   initData();
				   dialogVisible.value=false;
			   }
		   })


      } else {

		let insertData={
			username:formData.value.username,
			password:formData.value.password,
			real_name:formData.value.realName,
			dept_id:formData.value.department.at(-1),
			email:formData.value.email,
			phone:formData.value.phone,
			status:formData.value.status,
			create_by:1,
			role_id:formData.value.role,
		}
		console.log(insertData)
		proxy.$axios.post("/pcUser/insertPCUser",insertData)
		.then((serverData)=>{
			if(serverData.data.code==0){
				ElMessage.success('用户添加成功');
				initData();
				dialogVisible.value = false;
			}else{
				ElMessage.error(serverData.data.msg)
			}
		})
      }

    }
  });
};

// 删除用户（二次确认）
const handleDeleteUser = (row) => {
  ElMessageBox.confirm(
    `确定删除用户 ${row.username} 吗？`,
    '删除确认',
    { type: 'warning' }
  )
  .then(() => {
    proxy.$axios.delete(`/pcUser/deletePCUser/${row.pc_user_id}`)
	.then((serverdata)=>{
		if(serverdata.data.code==0){
			initData();
			ElMessage.success('用户已删除');
		}else{
      ElMessage.error(serverdata.data.msg)
    }
	})

  })
  .catch(() => {
    ElMessage.info('已取消删除');
  });
};



const roleList = ref([
	{
		label: '',
		value: '',
		roleType: '',
	}
])

const departmentList = ref([])
let roleTypeMap = {
	1: 'admin',
	4: 'admin',
}

const selectDepartment = () => {
	proxy.$axios.get("/api/v1/departments")
	.then((serverData) => {
		if (serverData.data.code == 0) {
			departmentList.value = serverData.data.data.map(item => ({
				label: item.name,
				value: item.dept_id,
				children: item.children.map(child => ({ label: child.name, value: child.dept_id })) || [],
			}))
			console.log(departmentList.value)
		}
	})
}

const selectRole = () => {
	proxy.$axios.get("/RoleController/getRoleList")
	.then((serverData) => {
		if (serverData.data.code == 0) {
			console.log(serverData.data.data)
			roleList.value = serverData.data.data.map(item => ({
				label: item.role_name,
				value: item.role_id,
				roleType: roleTypeMap[item.role_id] || 'doctor' // 默认设为admin
			}))
			console.log(roleList.value)
		}
	})
}

// 初始化加载数据
onMounted(() => {
  initData();
  selectRole();
  selectDepartment();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #1f2329;
}
.filter-card {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
}
.search-bar {
  display: flex;
  align-items: center;
}
.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
}
:deep(.el-table) { margin-top: 10px; }
:deep(.el-table-column__content .el-button) { margin-right: 8px; }
:deep(.el-table-column__content .el-button:last-child) { margin-right: 0; }
</style>
